package jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class SearchStu {
	public static void main(String[] args) throws Exception {
		List<Student> list =search("o",20,19);
		for (Student s : list) {
			System.out.println(s);
		}
	}

	private static List<Student> search(String name,int minAge,int maxAge) throws Exception{
		if(name==null){
			return getStu(minAge,maxAge);
		}else{
			return getStu(name,minAge,maxAge);
		}
	}

	private static List<Student> getStu(String name,int minAge,int maxAge) throws Exception{
		List<Student> list = new ArrayList<Student>();
		Connection con = null;
		PreparedStatement pst =null;
		ResultSet rs=null;
		String sql="select * from hh_stu where name like ? or age between ? and ?";
		try{
			con = DBUtil.open();
			pst=con.prepareStatement(sql);
			pst.setString(1, "%"+name+"%");
			pst.setInt(2, minAge);
			pst.setInt(3, maxAge);
			rs=pst.executeQuery();
			while(rs.next()){
				Student s = new Student();
				s.setAge(rs.getInt("age"));
				s.setName(rs.getString("name"));
				s.setBirthday(rs.getDate("birthday"));
				s.setId(rs.getInt("id"));
				list.add(s);
			}
		}finally{
			DBUtil.close(con, pst, rs);
		}
		return list;
	}

	private static List<Student> getStu(int minAge,int maxAge) throws Exception{
		List<Student> list = new ArrayList<Student>();
		Connection con = null;
		Statement stm =null;
		ResultSet rs=null;
		try{
			con = DBUtil.open();
			stm = con.createStatement();
			if(maxAge==0){
				rs = stm.executeQuery("select * from hh_stu");
			}else{
				rs = stm.executeQuery("select * from hh_stu where age between "+minAge+" and "+maxAge);
			}
			while(rs.next()){
				Student s = new Student();
				s.setAge(rs.getInt("age"));
				s.setName(rs.getString("name"));
				s.setBirthday(rs.getDate("birthday"));
				s.setId(rs.getInt("id"));
				list.add(s);
			}
		}finally{
			DBUtil.close(con, stm, rs);
		}
		return list;
	}
}
